<template lang="pug">
  Card.mouldSetting-con
    header.mouldSetting-header
      Form(ref="pageModelForm",:model="formValidate",:rules="ruleValidate",inline,:label-width="120")
        FormItem(label="页面模型名称：",prop="modelName")
          Input(v-model="formValidate.modelName",placeholder="页面模型名称",style="max-width:300px",:maxlength="50")
        FormItem(label='选择复制模板：',v-if="$route.query.status==='add'")
          Select(v-model="copyMouldValue",filterable,remote,:remote-method="handleCopyMouldOptions",
            :loading="copyMouldLoadingStatus",placeholder='选择复制模板',style="width:300px",@on-change='handleCopyMouldValue')
            Option(v-for="(option, index) in copyMouldOptions",:value="option.value",:key="index") {{option.label}}
      .mouldSetting-btnCon
        Button(type="error", v-if="$route.query.status==='modify'&&checkOutStatus", :disabled='checkStatus', @click='handleCheckOut') 签出
        Button(type="success", v-if="$route.query.status==='modify'&&checkInStatus", :disabled='!checkStatus || checkUserStatus',@click="handleCheckIn") 签入
        Button(type="primary", v-if="$route.query.status==='add'", @click="handleSave") 保存
        Button(@click="$router.push('/mould/index')") 返回
    section.mouldSetting-body
      Tabs(v-model='tabsName')
        TabPane(label='归属站点',name='0')
          siteBelong(ref='siteBelong',:sites='siteData')
        TabPane(label='基本属性',name='1')
          basicAttr(ref='basicAttr',:modelTypeLists='modelTypeLists',:contentTypeLists='contentTypeLists',:extractTypeLists='extractTypeLists',:refreshTypeLists='refreshTypeLists')
        TabPane(label='页面模型',name='2')
          pageModel(ref='pageModel',:extractTypeLists='extractTypeLists',:testStatusText='testStatusText',@handleModelBeta='handleModelBeta')
    Modal(title='社保短信验证码',v-model='authCodeModal',@on-ok='handleAuthCode')
      Form(ref='attributeForm',:model='formValidate',:rules='ruleValidate',:label-width='100')
        FormItem(label='短信验证码：',prop='name')
          Input(v-model='formValidate.authCode',autofocus)
</template>

<script>
import siteBelong from './components/siteBelong'
import basicAttr from './components/basicAttr'
import pageModel from './components/pageModel'
import { uuid } from '@/utils/utils'
import { asyncMould } from '../api'

export default {
  name: 'MouldSetting',
  components: { siteBelong, basicAttr, pageModel },
  data() {
    return {
      tabsName: '0',
      submitState: true,
      operate: true,
      authCodeModal: false,
      signKey: '',
      copyMouldLoadingStatus: false,
      copyMouldOptions: [],
      copyMouldValue: '',
      checkStatus: false,
      checkUserStatus: false,
      checkInStatus: false,
      checkOutStatus: false,
      siteData: [],
      modelTypeLists: [],
      contentTypeLists: [],
      extractTypeLists: [],
      refreshTypeLists: [],
      testStatusText: '',
      formValidate: {
        modelName: '',
        authCode: ''
      },
      ruleValidate: {
        modelName: [{ required: true, message: '请输入页面模型', trigger: 'blur' }],
        authCode: [{ required: true, message: '请输入短信验证码', trigger: 'blur' }]
      }
    }
  },
  created() {
    if (this.$route.query.status === 'modify') {
      const mouldPower = JSON.parse(sessionStorage.getItem('routes'))
        .filter(item => item.path === '/mould')[0]
        .children.filter(child => child.path === 'index')[0]
      if (mouldPower.meta['/pagemodel/checkin']) this.checkInStatus = true
      if (mouldPower.meta['/pagemodel/checkout']) this.checkOutStatus = true
      if (this.$route.query.checkType === '1') {
        this.checkStatus = true
        if (this.$route.query.updatePersonId !== sessionStorage.getItem('userId')) this.checkUserStatus = true
      }
    }
    ;(async () => {
      const [modelTypeLists, extractTypeLists, contentTypeLists, refreshTypeLists] = await Promise.all([
        asyncMould.querytype({ data: { typeId: 1 } }),
        asyncMould.querytype({ data: { typeId: 3 } }),
        asyncMould.querytype({ data: { typeId: 4 } }),
        asyncMould.querytype({ data: { typeId: 10 } })
      ]).catch(error => {})
      this.modelTypeLists = modelTypeLists.data.data
      this.extractTypeLists = extractTypeLists.data.data
      this.contentTypeLists = contentTypeLists.data.data
      this.refreshTypeLists = refreshTypeLists.data.data
      if (this.$route.query.status === 'add') {
        this.$refs.basicAttr.basicAttrData.modelType = this.modelTypeLists[0].itemType
        this.$refs.basicAttr.basicAttrData.urlExtractRuleType = this.extractTypeLists[0].itemType
        this.$refs.basicAttr.basicAttrData.contentType = this.contentTypeLists[0].itemType
        this.$refs.basicAttr.browserParameter.refreshType = this.refreshTypeLists[0].itemType
      }
      if (this.$route.query.status === 'modify') this.handleQuery(this.$route.query.modelId)
    })()
    this.handleListSiteName()
    this.$nextTick(() => {
      if (this.$route.query.status === 'modify') {
        this.$store.dispatch('breadcrumb/getBreadCrumb', [{ name: '模板中心' }, { name: '数据采集模板' }, { name: '修改' }])
      } else {
        this.$store.dispatch('breadcrumb/getBreadCrumb', [{ name: '模板中心' }, { name: '数据采集模板' }, { name: '新增' }])
      }
    })
  },
  methods: {
    handleListSiteName: async function() {
      try {
        const res = await asyncMould.listsitename({ data: {} })
        this.siteData = res.data.data
        if (this.$route.query.status === 'add') this.$refs['siteBelong'].siteData.siteId = res.data.data[0].siteId
      } catch (error) {}
    },
    handleQuery: async function(modelId) {
      try {
        const res = await asyncMould.query({ data: { modelId } })
        const { browserRefreshConfigureEntity, pageTurningConfigureEntity, pageModelPropertyEntity, pageModelCleanDataRuleList } = res.data.data
        ;({
          modelName: this.formValidate.modelName,
          siteId: this.$refs.siteBelong.siteData.siteId,
          modelType: this.$refs.basicAttr.basicAttrData.modelType,
          contentType: this.$refs.basicAttr.basicAttrData.contentType,
          modelRegularExpression: this.$refs.basicAttr.basicAttrData.modelRegularExpression,
          urlsAllowCrawlRegex: this.$refs.basicAttr.basicAttrData.urlsAllowCrawlRegex,
          urlsNotAllowCrawlRegex: this.$refs.basicAttr.basicAttrData.urlsNotAllowCrawlRegex,
          needLogin: this.$refs.basicAttr.basicAttrData.needLogin,
          urlExtractable: this.$refs.basicAttr.basicAttrData.urlExtractable,
          urlExtractRuleType: this.$refs.basicAttr.basicAttrData.urlExtractRuleType,
          urlExtractRule: this.$refs.basicAttr.basicAttrData.urlExtractRule,
          browserCrawlable: this.$refs.basicAttr.basicAttrData.browserCrawlable,
          pageTurningable: this.$refs.basicAttr.basicAttrData.pageTurningable
        } = res.data.data)
        if (pageModelPropertyEntity !== null && pageModelPropertyEntity.length !== 0) {
          let newData = []
          pageModelPropertyEntity.forEach(item => {
            pageModelCleanDataRuleList.forEach(ele => {
              if (item.propertyId === ele.modelAttrId) {
                item.jsonPath = ele.jsonPath
                item.regex = ele.regex
              }
            })
            newData[item.sortedId - 1] = item
          })
          this.$refs['pageModel'].handleFormatQueryData(newData)
        }
        if (browserRefreshConfigureEntity !== null && browserRefreshConfigureEntity.length !== 0) {
          if (this.$refs.basicAttr.basicAttrData.browserCrawlable === 2) this.$refs.basicAttr.browserParameter = browserRefreshConfigureEntity[0]
        } else {
          this.$refs.basicAttr.browserParameter.refreshType = this.refreshTypeLists[0].itemType
        }
        if (pageTurningConfigureEntity !== null && pageTurningConfigureEntity.length !== 0) {
          if (this.$refs.basicAttr.basicAttrData.pageTurningable === 1) this.$refs.basicAttr.pageTurningParameter = pageTurningConfigureEntity[0]
        }
      } catch (error) {}
    },
    handleCheckOut: async function() {
      try {
        await asyncMould.checkout({ data: { modelId: this.$route.query.modelId } })
        this.$Message.success('签出成功')
        this.checkStatus = true
      } catch (error) {}
    },
    handleCheckIn() {
      this.operate = false
      this.$refs['pageModelForm'].validate(async valid => {
        if (valid) {
          const { pageModelResult, browserParameter, pageTurningParameter, pageModelPropertyResult, cleanDataRule } = this.handleCleanRequestData()
          if (this.handleValidate(pageModelPropertyResult)) {
            try {
              await asyncMould.checkin({ data: { pageModelResult, browserParameter, pageTurningParameter, pageModelPropertyResult, cleanDataRule } })
              this.$Message.success('签入成功')
              this.$router.push('/mould/index')
            } catch (error) {}
          }
        }
      })
    },
    handleCopyMouldValue() {
      this.handleQuery(this.copyMouldValue)
    },
    handleCopyMouldOptions: async function(query) {
      if (query !== '') {
        try {
          this.copyMouldOptions = []
          this.copyMouldLoadingStatus = true
          const res = await asyncMould.queryCopyTop({ data: { modelName: query } })
          this.copyMouldOptions = res.data.data.map(item => {
            return { value: item.modelId, label: item.modelName }
          })
          this.copyMouldLoadingStatus = false
        } catch (error) {
          this.copyMouldLoadingStatus = false
        }
      }
    },
    handleValidate(pageModelPropertyResult) {
      if (this.$refs['basicAttr'].basicAttrData.modelType === 1 && this.$refs['basicAttr'].basicAttrData.urlExtractRule === '') {
        this.$refs['basicAttr'].basicAttrData.urlExtractable = 1
        this.$Message.warning('抽取页面Url时，抽取Url不能为空')
        return false
      }
      if (this.$refs['basicAttr'].basicAttrData.modelType === 2 && pageModelPropertyResult === '') {
        this.$Message.warning('抽取页面属性时，页面模型属性或属性组不能为空')
        return false
      }
      if (!this.submitState) {
        return false
      }
      return true
    },
    handleSave() {
      this.operate = false
      this.$refs['pageModelForm'].validate(valid => {
        if (valid) {
          this.$refs['basicAttr'].$refs['basicData'].validate(async valid => {
            if (valid) {
              const { pageModelResult, browserParameter, pageTurningParameter, pageModelPropertyResult, cleanDataRule } = this.handleCleanRequestData()
              if (this.handleValidate(pageModelPropertyResult)) {
                try {
                  await asyncMould.add({ data: { pageModelResult, browserParameter, pageTurningParameter, pageModelPropertyResult, cleanDataRule } })
                  this.$Message.success('添加成功')
                  this.$router.push('/mould/index')
                } catch (error) {}
              }
            } else {
              this.tabsName = '1'
            }
          })
        }
      })
    },
    handleAuthCode: async function() {
      const { pageModelResult: pageModelParameter, pageModelPropertyResult: pageModelProperties, cleanDataRule: pageModelCleanDataRules } = this.handleCleanRequestData()
      try {
        await asyncMould.socialSecuritySmsCode({
          data: {
            pageModelParameter,
            pageModelProperties,
            pageModelCleanDataRules: this.$refs.pageModel.betaLabel === 3 ? pageModelCleanDataRules : '',
            verifyUrl: this.$refs['pageModel'].testUrlAddress,
            smsCode: this.formValidate.authCode,
            signKey: this.signKey
          },
          timeout: 200000
        })
      } catch (error) {}
    },
    handleModelBeta: async function() {
      this.operate = true
      const {
        pageModelResult: pageModelParameter,
        browserParameter,
        pageTurningParameter,
        pageModelPropertyResult: pageModelProperties,
        cleanDataRule: pageModelCleanDataRules
      } = this.handleCleanRequestData()
      delete pageModelParameter.modelName
      try {
        this.$refs.pageModel.attrSetData = ''
        this.$refs.pageModel.extUrlsData = ''
        this.$refs.pageModel.pageTurningUrlsData = ''
        this.testStatusText = '验证中...'
        let res
        switch (this.$refs.pageModel.betaLabel) {
          case 0:
            res = await asyncMould.generalModelVerify({
              data: Object.assign({ verifyUrl: this.$refs.pageModel.testUrlAddress }, { pageModelParameter, pageModelProperties, browserParameter, pageTurningParameter })
              // timeout: 200000
            })
            break
          case 1:
            res = await asyncMould.socialSecurityModelVerify({
              data: Object.assign({ verifyUrl: this.$refs.pageModel.testUrlAddress }, { pageModelParameter, pageModelProperties }),
              timeout: 200000
            })
            if (res.data.respCode === '208') {
              this.authCodeModal = true
              this.signKey = res.data.data
            }
            break
          case 2:
            if (this.submitState) {
              res = await asyncMould.generalModelVerify({
                data: Object.assign(
                  { verifyUrl: this.$refs.pageModel.testUrlAddress },
                  {
                    pageModelParameter,
                    pageModelProperties,
                    browserParameter,
                    pageTurningParameter,
                    pageModelCleanDataRules
                  }
                ),
                timeout: 200000
              })
            }
            break
          case 3:
            if (this.submitState) {
              res = await asyncMould.socialSecurityModelVerify({
                data: Object.assign({ verifyUrl: this.$refs.pageModel.testUrlAddress }, { pageModelParameter, pageModelProperties, pageModelCleanDataRules }),
                timeout: 200000
              })
              if (res.data.respCode === '208') {
                this.authCodeModal = true
                this.signKey = res.data.data
              }
            }
            break
        }
        this.testStatusText = '验证成功'
        this.$refs.pageModel.attrSetData = res.data.data
        this.$refs.pageModel.extUrlsData = res.data.extUrls
        this.$refs.pageModel.pageTurningUrlsData = res.data.pageTurningUrls
        this.$refs.pageModel.loading = false
      } catch (error) {
        this.testStatusText = '验证失败'
        this.$refs.pageModel.loading = false
      }
    },
    handleCleanRequestData() {
      /**
       * @description 数据格式化清洗
       * @param {String} pageModelResult 基本属性
       * @param {String} browserParameter 浏览器采集
       * @param {String} pageTurningParameter 翻页
       * @param {Array} pageModelPropertyResult 属性和属性组
       * @param {Array} cleanDataRule 清洗规则
       */
      let [pageModelResult, browserParameter, pageTurningParameter, pageModelPropertyResult, cleanDataRule] = ['', '', '', [], []]
      pageModelResult = Object.assign({ siteId: this.$refs['siteBelong'].siteData.siteId, modelName: this.formValidate.modelName }, this.$refs['basicAttr'].basicAttrData)
      if (this.$refs['basicAttr'].basicAttrData.browserCrawlable === 2) browserParameter = this.$refs['basicAttr'].browserParameter
      if (this.$refs['basicAttr'].basicAttrData.pageTurningable === 1) pageTurningParameter = this.$refs['basicAttr'].pageTurningParameter
      if (this.$route.query.status === 'modify') {
        pageModelResult = Object.assign({ modelId: this.$route.query.modelId }, pageModelResult)
        if (this.$refs['basicAttr'].basicAttrData.browserCrawlable === 2) browserParameter = Object.assign({ modelId: this.$route.query.modelId }, browserParameter)
        if (this.$refs['basicAttr'].basicAttrData.pageTurningable === 1) pageTurningParameter = Object.assign({ modelId: this.$route.query.modelId }, pageTurningParameter)
      }
      const filterPageAttr = pageAttrData => {
        pageAttrData.forEach(item => {
          let [{ propertyId: modelAttrId, parentId, jsonPath, regex }, modifyCleanDataRule] = [item, {}]
          modifyCleanDataRule = { modelAttrId, parentId, jsonPath, regex }
          if (this.$route.query.status === 'modify') modifyCleanDataRule = Object.assign({ modelId: this.$route.query.modelId }, modifyCleanDataRule)
          cleanDataRule.push(modifyCleanDataRule)
          pageModelPropertyResult.push(item)
          if (item.children) filterPageAttr(item.children)
        })
        return pageModelPropertyResult
      }
      const deletePageAttrChildren = pageAttrData => {
        for (let i in pageAttrData) {
          pageAttrData[i].sortedId = i - 0 + 1
          if (pageAttrData[i].children) delete pageAttrData[i].children
          if (pageAttrData[i].matchExpression === '') {
            this.submitState = false
            this.$Message.warning('页面模型内容不能为空')
            break
          } else if (pageAttrData[i].jsonPath === '' && this.operate && (this.$refs['pageModel'].betaLabel === 2 || this.$refs['pageModel'].betaLabel === 3)) {
            this.submitState = false
            this.$Message.warning('清洗规则jsonPath不能为空')
            break
          } else if (pageAttrData[i].regex === '' && this.operate && (this.$refs['pageModel'].betaLabel === 2 || this.$refs['pageModel'].betaLabel === 3)) {
            this.submitState = false
            this.$Message.warning('清洗规则正则表达式不能为空')
            break
          } else if (parseInt(i) === pageAttrData.length - 1) {
            this.submitState = true
            return (pageModelPropertyResult = pageAttrData)
          }
        }
      }
      deletePageAttrChildren(filterPageAttr(JSON.parse(JSON.stringify(this.$refs['pageModel'].pageModelItems))))
      return {
        pageModelResult: pageModelResult === '' ? '' : JSON.stringify(pageModelResult),
        browserParameter: browserParameter === '' ? '' : JSON.stringify(browserParameter),
        pageTurningParameter: pageTurningParameter === '' ? '' : JSON.stringify(pageTurningParameter),
        pageModelPropertyResult: pageModelPropertyResult.length === 0 ? '' : JSON.stringify(pageModelPropertyResult),
        cleanDataRule: cleanDataRule.length === 0 ? '' : JSON.stringify(cleanDataRule)
      }
    }
  }
}
</script> 
<style lang="scss">
@import './index.scss';
</style>